package generate

import (
	"bytes"
	"context"
	"fmt"

	"gitee.com/mchongjs/gin-admin-cli/util"
)

func getModelFileName(dir, name string) string {
	fullname := fmt.Sprintf("%s/internal/app/model/m_%s.go", dir, util.ToLowerUnderlinedNamer(name))
	return fullname
}

// 生成model文件
func genModel(ctx context.Context, pkgName, dir string, item TplItem) error {

	name := item.StructName
	comment := item.Comment
	hasselect := item.HasSelect

	data := map[string]interface{}{
		"PkgName": pkgName,
		"Name":    name,
		"Comment": comment,
	}
	finalbuf := new(bytes.Buffer)
	buf, err := execParseTpl(modelTpl, data)
	if err != nil {
		return err
	}
	finalbuf.Write(buf.Bytes())
	buf.Reset()
	if hasselect {
		buf, err = execParseTpl(modelselectTpl, data)
		if err != nil {
			return err
		}
		finalbuf.Write(buf.Bytes())
		buf.Reset()
	}

	buf, err = execParseTpl(modelTpl2, data)
	if err != nil {
		return err
	}

	finalbuf.Write(buf.Bytes())
	buf.Reset()

	fullname := getModelFileName(dir, name)
	err = createFile(ctx, fullname, finalbuf)
	if err != nil {
		return err
	}

	fmt.Printf("文件[%s]写入成功\n", fullname)

	return execGoFmt(fullname)
}

const modelTpl = `
package model

import (
	"context"

	"{{.PkgName}}/internal/app/schema"
)

// I{{.Name}} {{.Comment}}存储接口
type I{{.Name}} interface {
	// 查询数据
	Query(ctx context.Context, params schema.{{.Name}}QueryParam, opts ...schema.{{.Name}}QueryOptions) (*schema.{{.Name}}QueryResult, error)
`
const modelselectTpl = `
	// 选择数据（下拉用）
	Select(ctx context.Context, params schema.{{.Name}}QueryParam) (*schema.{{.Name}}_shortQueryResult, error)
`

const modelTpl2 = `
	// 查询指定数据
	Get(ctx context.Context, recordID int, opts ...schema.{{.Name}}QueryOptions) (*schema.{{.Name}}, error)
	// 创建数据
	Create(ctx context.Context, item schema.{{.Name}}) (int, error)
	// 更新数据
	Update(ctx context.Context, recordID int, item schema.{{.Name}}) error
	// 删除数据
	Delete(ctx context.Context, recordID int) error
}

`
